import 'dart:convert';
import 'dart:developer';

enum PageLoadType { noData, normal, noMore, error }

class PageGetRspModel<T> {
  final List<T> data;
  final PagingRspModel pagingRspModel;

  PageGetRspModel(this.data, this.pagingRspModel);
}

void tryCatch(Function? f) {
  try {
    f?.call();
  } catch (e, stack) {
    log('$e');
    log('$stack');
  }
}

class FFConvert {
  FFConvert._();

  static T? Function<T extends Object?>(dynamic value) convert =
      <T>(dynamic value) {
    if (value == null) {
      return null;
    }
    return json.decode(value.toString()) as T?;
  };
}

T? asT<T extends Object?>(dynamic value, [T? defaultValue]) {
  if (value is T) {
    return value;
  }
  try {
    if (value != null) {
      final String valueS = value.toString();
      if ('' is T) {
        return valueS as T;
      } else if (0 is T) {
        return int.parse(valueS) as T;
      } else if (0.0 is T) {
        return double.parse(valueS) as T;
      } else if (false is T) {
        if (valueS == '0' || valueS == '1') {
          return (valueS == '1') as T;
        }
        return (valueS == 'true') as T;
      } else {
        return FFConvert.convert<T>(value);
      }
    }
  } catch (e, stackTrace) {
    log('asT<$T>', error: e, stackTrace: stackTrace);
    return defaultValue;
  }

  return defaultValue;
}

class PagingRspModel {
  PagingRspModel({
    this.limit,
    this.offset,
    this.hasMore,
  });

  factory PagingRspModel.fromJson(Map<String, dynamic> json) => PagingRspModel(
        limit: asT<int?>(json['limit']),
        offset: asT<int?>(json['offset']),
        hasMore: asT<int?>(json['has_more']),
      );

  int? limit;
  int? offset;
  int? hasMore;

  PageLoadType get pageLoadType {
    if (hasMore == 1) {
      return PageLoadType.normal;
    } else {
      return PageLoadType.noMore;
    }
  }

  @override
  String toString() {
    return jsonEncode(this);
  }

  Map<String, dynamic> toJson() => <String, dynamic>{
        'limit': limit,
        'offset': offset,
        'has_more': hasMore,
      };
}
